package mastermind.game;

import java.io.Serializable;

import mastermind.net.Protocol;

/**
 * Represents a row of coloured pieces
 */
public class Pieces implements Serializable {
	private static final long serialVersionUID = -1239150663347692144L;
	private char[] value;

	public Pieces() {
		this(Protocol.SECRET_DEFAULT_LENGTH);
	}

	public Pieces(int size) {
		value = new char[size];
	}

	public Pieces(char[] pieces) {
		value = pieces;
	}

	/**
	 * Get the piece at given position in this row
	 */
	public char getPiece(int position) {
		return value[position];
	}

	/** Get all pieces in this row */
	public char[] getPieces() {
		return value;
	}

	/** Get size of this row */
	public int getLength() {
		return value.length;
	}

	/**
	 * Compare two rows and get peg feedback.
	 * 
	 * @param p
	 *            Pieces to compare to
	 * @return A string to indicate same position/colour pieces. A 'b' is same
	 *         colour and position, 'w' is correct colour only.
	 * @throws PieceException
	 *             If pieces are of different lengths
	 */
	public String feedback(Pieces p) throws GameException {
		if (p.getLength() != getLength())
			throw new GameException("Pieces are of differing lengths");

		// make a copy of the pieces we can modify
		char[] temp = value.clone();
		String pegs = "";
		for (int i = 0; i < getLength(); i++) {
			/* both colour and position are correct */
			if (temp[i] == p.getPiece(i)) {
				// don't look at this piece again
				temp[i] = '0';
				pegs += 'b';
				continue;
			}
			/* only colour is correct */
			for (int j = 0; j < getLength(); j++) {
				if (temp[j] == p.getPiece(i)) {
					// don't look at this piece again
					temp[j] = '0';
					pegs += 'w';
					break;
				}
			}
		}

		return pegs;
	}

	/**
	 * Generate a random set of Pieces
	 * 
	 * @param available
	 *            Available colours to use
	 * @param length
	 *            Length of Pieces
	 */
	public static Pieces randomPieces(String[] available, int length) {
		// TODO check for <= 0 length
		char[] pieces = new char[length];
		int r;
		for (int i = 0; i < length; i++) {
			r = (int) (Math.random() * available.length);
			pieces[i] = available[r].charAt(0);
		}
		return new Pieces(pieces);
	}
	
	public String toString() {
		return new String(value);
	}
}
